﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Vabp.Helper;
using Vabp.User.Dto;
using Vabp.Users;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using Vabp.Infrastructure.Redis;
using Volo.Abp;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Vabp.Login
{
    public class LoginService: ApplicationService, ILoginService
    {
        private readonly IRepository<LoginUser,int> loginUserRepository;
//        private readonly IRedisService redisService;

        public LoginService(IRepository<LoginUser,int> loginUserRepository)
        {
            this.loginUserRepository = loginUserRepository;
//            this.redisService = redisService;
        }

        public async Task<LoginUserDto> CheckUserNameAndPasswordAsync(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName)) throw new UserFriendlyException("请输入用户名");
            if(string.IsNullOrEmpty(password)) throw new UserFriendlyException("请输入密码");

            

            //查询用户
            LoginUser user = await loginUserRepository.Include(u=>u.UserRoles).Where(u => u.UserName == userName).FirstOrDefaultAsync();
            //校验用户
            if(user == null) throw new UserFriendlyException("当前用户不存在,请核对用户名");
            if(!user.IsEnable) throw new UserFriendlyException("当前用户不可用,请联系管理员开通");
            string encryptedStr = CommonHelper.Encrypted(password);
            if (user.Password != encryptedStr) throw new UserFriendlyException("当前用户无法登入,密码不正确");

            return ObjectMapper.Map<LoginUser, LoginUserDto>(user);

        }

    }
}
